#define _GNU_SOURCE
#include "app_ble.h"
#include "app_serial.h"
#include <string.h>
#include <unistd.h>

static char Total_data[512];
static int Total_data_len = 0;
static char Frame_header[2] = {0xF1, 0xDD};

static int App_BLE_WaitAsk(Device_t *device)
{
    usleep(50 * 1000);
    char ask[4] = {0};
    read(device->fd, ask, 4);
    if(memcmp(ask, "OK\r\n", 4) == 0)
    {
        return 0;
    }
    return -1;
}

int App_BLE_Status(Device_t *device)
{
    write(device->fd, "AT\r\n", 4);
    if(App_BLE_WaitAsk(device) == -1)
    {
        log_error("蓝牙模块不可用");
        return -1;
    }
    log_debug("蓝牙模块可用");
    return 0;
}

int App_BLE_ModifyName(Device_t *device, char *name)
{
    char buf[100] = {0};
    sprintf(buf, "AT+NAME%s\r\n", name);
    write(device->fd, buf, strlen(buf));
    if(App_BLE_WaitAsk(device) == -1)
    {
        log_error("蓝牙模块改名失败");
        return -1;
    }
    log_debug("蓝牙模块改名成功");
    return 0;
}

int App_BLE_SetBaudRate(Device_t *device, BLE_BaudRate br)
{
    char buf[15] = {0};
    sprintf(buf, "AT+BAUD%c\r\n", br);
    write(device->fd, buf, strlen(buf));
    if(App_BLE_WaitAsk(device) == -1)
    {
        log_error("蓝牙模块改波特率失败");
        return -1;
    }
    log_debug("蓝牙模块改波特率成功");
}

int App_BLE_Reset(Device_t *device)
{
    write(device->fd, "AT+RESET\r\n", 10);
    if(App_BLE_WaitAsk(device) == -1)
    {
        log_error("蓝牙模块复位失败");
        return -1;
    }
    log_debug("蓝牙模块复位成功");
    return 0;
}

int App_BLE_SetNetID(Device_t *device, char *netid)
{
    char buf[100] = {0};
    sprintf(buf, "AT+NETID%s\r\n", netid);
    write(device->fd, buf, strlen(buf));
    if(App_BLE_WaitAsk(device) == -1)
    {
        log_error("蓝牙模块设置组网ID失败");
        return -1;
    }
    log_debug("蓝牙模块设置组网ID成功");
    return 0;
}

int App_BLE_SetMaddr(Device_t *device, char *maddr)
{
    char buf[100] = {0};
    sprintf(buf, "AT+MADDR%s\r\n", maddr);
    write(device->fd, buf, strlen(buf));
    if(App_BLE_WaitAsk(device) == -1)
    {
        log_error("蓝牙模块设置MAC地址失败");
        return -1;
    }
    log_debug("蓝牙模块设置MAC地址成功");
    return 0;
}

int App_BLE_Init(Device_t *device)
{
    device->post_read = App_BLE_PostRead;
    device->pre_write = App_BLE_PreWrite;
    // 初始化串口
    App_Serial_Init(device);

    if(App_BLE_Status(device) == -1)
    {
        log_error("蓝牙模块不可用");
        return -1;
    }
    // 设置蓝牙模块
    App_BLE_SetBaudRate(device, BLE_BR115200);
    App_BLE_ModifyName(device, "Flight");
    App_BLE_SetNetID(device, "1111");
    App_BLE_SetMaddr(device, "2003");
    App_BLE_Reset(device);
    sleep(1);
    // 设置串口
    App_Serial_SetBaudRate(device, BR_115200);
    tcflush(device->fd, TCIOFLUSH);

    if(App_BLE_Status(device) == -1)
    {
        log_error("蓝牙模块初始化失败");
        return -1;
    }
    // 设置串口为阻塞模式
    App_Serial_SetBlock(device, Block);
    tcflush(device->fd, TCIOFLUSH);
    log_debug("蓝牙模块初始化成功");
    return 0;
}

int App_BLE_PostRead(char *data, int len)
{
    // 把每次数据存起来
    memcpy(Total_data + Total_data_len, data, len);
    Total_data_len += len;
    if(Total_data_len < 8)
    {
        log_error("蓝牙数据最小长度错误");
        return 0;
    }
    log_debug("total data:%s, len:%d", Total_data, Total_data_len);
    for (int i = 0; i < Total_data_len - 7; i++)
    {
        if(memcmp(Total_data + i, Frame_header, 2) == 0)
        {
            if(i > 0)
            {
                // 帧头不在头部,需要把前面的数据移除
                memmove(Total_data, Total_data + i, Total_data_len - i);
                Total_data_len -= i;
            }
            if( Total_data_len > 3 + Total_data[2])
            {
                // 帧头后面还有数据,数据帧完整
                data[0] = '1';
                data[1] = '2';
                data[2] = Total_data[2] - 4 + '0';
                memcpy(data + 3, Total_data + 3, 2);
                memcpy(data + 5, Total_data + 7, Total_data[2] - 4);
                log_debug("发送蓝牙数据为data:%.*s", strlen(data), data);
                return strlen(data);
            }
            log_debug("接收到帧头,但是数据帧不完整，继续接收");
            return 0;
        }
    }
    return 0;
}

int App_BLE_PreWrite(char *data, int len)
{
    if(len < 6)
    {
        log_error("蓝牙数据错误");
        return -1;
    }
    // 确定连接模式不是蓝牙,再处理数据
    if(data[0] != '1')
    {
        return 0;
    }
    int Ble_data_len = 12 + (data[2] - '0');
    char Ble_data[Ble_data_len];
    memcpy(Ble_data, "AT+MESH", 8);
    memcpy(Ble_data + 8, data + 3, 2);
    memcpy(Ble_data + 10, data + 5, data[2] - '0');
    memcpy(Ble_data + 10 + (data[2] - '0'), "\r\n", 2);
    memset(data, 0, len);
    memcpy(data, Ble_data, Ble_data_len);
    log_debug("ble data:%.*s", Ble_data_len, data);
    return Ble_data_len;
}

